var express = require("express");
var router = express.Router();
var { ArticleModel } = require("../model/mtg");
var { courseModel, conModel, sederModel } = require("../model/zw");
// var {subjectModel}=require('../model/kys')

/* GET home page. */
router.post("/add", (req, res) => {
  courseModel.create(req.body);
  res.send({
    code: 200,
    msg: "add okk",
  });
});

router.get("/show", async function (req, res, next) {
  let { list } = req.query;
  // console.log(list);
  if (!Array.isArray(list)) {
    list = [list];
  }
  let tit = await conModel.find({ _id: { $in: list } });
  
  let courses = await courseModel.find({ cid: { $in: list } });

  let cateCourses = {};
  for (const course of courses) {
    if (!cateCourses[course.cid]) {
      cateCourses[course.cid] = [];
    }

    if (cateCourses[course.cid].length < 3) {
      cateCourses[course.cid].push(course);
    }
  }

  let result = tit.map((conCategory) => ({
    title: conCategory.title,
    cid: conCategory._id,
    children: cateCourses[conCategory._id] || [],
  }));
  result.forEach((category) => {
    if (category.children.length > 3) {
      category.children.length = 3;
    }
  });
  const artdata = await ArticleModel.find().limit(5);
  let flashHotCours = await courseModel
    .find({ discount: { $ne: 1 } })
    .sort({ num: -1 })
    .limit(5);

  let firlevel = await sederModel.find();
  let seclevel = await conModel.find();

 let clist = await sederModel.aggregate([
  {
    $lookup: {
      from: "con", // 'sedermodels'应替换为您的实际集合名
      localField: "_id",
      foreignField: "bid",
      as: "children",
    },
  },
]);

  res.send({
    code: 200,
    msg: "200 akk",
    artdata,
    flashHotCours,
    firlevel,
    seclevel,
    result,
    tit,
    clist
  });
});

router.get("/detail", async (req, res) => {
  // console.log(req.query, "detail");
  let { categroy } = req.query;
  let data = [];
  switch (categroy) {
    case "热门好课":
      data = await courseModel.find().sort({ num: -1 }).limit(100);
      break;
    case "精品课程":
      data = await courseModel
        .find({ price: { $ne: 0 } })
        .sort({ num: -1 })
        .limit(100);
      break;
    case "限时优惠":
      data = await courseModel.aggregate([
        { $match: { discount: { $ne: 1 } } },
        { $limit: 100 },
      ]);
      break;
    case "免费专区":
      // console.log(1);
      data = await courseModel.aggregate([
        { $match: { price: 0 } },
        { $limit: 100 },
      ]);
      // console.log(data);
      break;
    default:
      let cid = await conModel.find({ title: categroy });
      data = await courseModel.find({ cid });
      break;
  }

  res.send({
    code: 200,
    msg: "200 akk",
    data,
  });
});

module.exports = router;
